package com.xzy.ccc.postprocessor;

import com.xzy.ccc.bean.ExampleBean;
import com.xzy.ccc.bean.NewImplementation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 利用BeanFactoryPostProcessor可以实现下列功能：
 * <ol>
 *     <li>动态修改Bean定义的属性值</li>
 *     <li>替换Bean的实现类</li>
 *     <li>根据条件移除或添加Bean的定义</li>
 *     <li>动态注入属性值</li>
 *     <li>自定义作用域</li>
 * </ol>
 *
 * @author xzy.xiao
 * @date 2023/7/5  19:25
 */
public class CustomBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 动态修改Bean定义的属性值
        if (bean instanceof ExampleBean) {
            ExampleBean exampleBean = (ExampleBean) bean;
            exampleBean.setDynamicProperty("newValue");
        }

        // 替换Bean的实现类
        if (bean instanceof ExampleBean) {
            return new NewImplementation();
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 根据条件移除或添加Bean的定义
        if (shouldRemove(bean, beanName)) {
            return null; // 返回null表示移除该Bean定义
        }

        // 动态注入属性值
        if (bean instanceof ExampleBean) {
            ExampleBean exampleBean = (ExampleBean) bean;
            exampleBean.setDynamicProperty("dynamicValue");
        }

        return bean;
    }

    private boolean shouldRemove(Object bean, String beanName) {
        // 条件判断...
        return false;
    }
}
